package cn.dugt.hotel.controller;

import cn.dugt.hotel.entity.User;
import cn.dugt.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    public UserService userService;
//首页
@RequestMapping(value="/index",method=RequestMethod.GET)
    public String  list(Map map,String username){
    map.put("username",username);
    return "home/index";
}

//登录
    @RequestMapping(value="/login",method=RequestMethod.GET)
    public String  login() {
    return "home/login";
    }

    //注册
    @RequestMapping(value = "/reg",method=RequestMethod.GET)
    public  String  reg(){

    return "home/reg";
    }
//登录操作
    @RequestMapping(value = "/login" ,method = {RequestMethod.POST})
    public String loginuser(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("role") int role, Map map, Model model, @ModelAttribute User user){
         if(username==null){
            map.put("error","用户名不能为空");
            return  "home/login";
        }
        else if(password==null){
            map.put("error","密码不能为空");
            return  "home/login";
        }
        if(role==1){
            if(username!=null&&password!=null&&userService.finduser(username,password)==null) {
                map.put("error","用户名或密码错误");
                return "home/login";

            }
            else {
                map.put("username", username);
                map.put("role",role);
                return "home/index";
            }
        }
        if(role==0){
            if(username!=null&&password!=null&&userService.finduser(username,password)==null) {
                map.put("error","用户名或密码错误");
                return "home/login";

            }
            else {
                map.put("username", username);
                map.put("role",role);
                model.addAttribute("username",username);
                return "home/index";
            }
        }
        return "home/login";
    }




    @RequestMapping(value = "/reg",method = {RequestMethod.POST})
    public  String reguser(User user, Map map){
        if(userService.findusername(user.getUsername())!=null){
            map.put("msg","用户名已存在");
            return "home/reg";
        }
        if(userService.findusername(user.getUsername())==null){
            userService.addUser(user);
        }
        return "home/login";
    }

}
